package com.ijunfu.spring.bean._04_bean_controller_advice.contoller;

import com.ijunfu.spring.bean._04_bean_controller_advice.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @title  : 
 * @author : ijunfu <ijunfu@163.com>
 * @date   : 2023/10/31 17:12
 * @version: 1.0
 * @motto  : 位来可期 - 世界很大，我想看看
 *
 */
@Slf4j
//@ControllerAdvice
@RestControllerAdvice
public class MyControllerAdvice {

    // 请求参数预处理
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
    }

    // 预设全局参数
    @ModelAttribute
    public void presetParam(Model mode) {
        mode.addAttribute("author", "ijunfu");
    }

    // 全局异常处理
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException ex) {
        log.error("参数错误");
        return Result.error();
    }

    // 全局异常处理
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex) {
        log.error("系统错误");
        return Result.error();
    }
}
